package cn.td0f7.android.wangzhongcourse.broadcastreceiver;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import cn.td0f7.android.wangzhongcourse.R;

public class BroadcastReceiverActivity extends AppCompatActivity {
    private MyBroadcastReceiver myBroadcastReceiver;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast_receiver);
        btn = findViewById(R.id.btn);
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter itFilter = new IntentFilter();
//        itFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//网络变化
        itFilter.addAction("cn.td0f7.android.test.broadcast");//自定义广播
        registerReceiver(myBroadcastReceiver, itFilter);//监听

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("cn.td0f7.android.test.broadcast");
                intent.putExtra("data", "自定义广播");
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }
}